<?php  namespace App\Models;

use Input, Config, Auth, DB, Validator,Cache,Log;

class Stopwords extends BaseModel {

    protected $table = 'stopwords';
    protected $primaryKey = 'stopwords_id';
	
	//替换给定字符串
	public function replace($organization_id,$target){
        $cacheArr = array();
        $cacheArr['cacheTag'] = array(0 => 'Stopwords');
        $cacheArr['cacheKey'] = 'Stopwords'.'type1';
         if (Cache::tags($cacheArr['cacheTag'])->has($cacheArr['cacheKey'])) {
            $stopwordses = Cache::tags($cacheArr['cacheTag'])->get($cacheArr['cacheKey']);
        } else {
            $stopwordses = $this->select('stopwords_id','words','replace')
                ->where('status', '=', '1')
                ->where('type', '=', '1')
                ->where('organization_id','=',$organization_id)
                ->get();
            Cache::tags($cacheArr['cacheTag'])->put($cacheArr['cacheKey'], $stopwordses, $this->CacheTime['Stopwords']);
        }
		foreach($stopwordses as $stopwords){
			foreach (explode(',', $stopwords->words) as $word){
				$replace = $stopwords->replace == '*' ? str_repeat('*', mb_strlen($word, 'utf-8')) : $stopwords->replace;
				$target = str_replace($word, $replace, $target);
			}
		}
		return $target;
	}
    
    public function isExistStopWords($target,$organization_id=9){
        $cacheArr = array();
        $cacheArr['cacheTag'] = array(0 => 'Stopwords');
        $cacheArr['cacheKey'] = 'Stopwords'.'type2';
         if (Cache::tags($cacheArr['cacheTag'])->has($cacheArr['cacheKey'])) {
            $stopwordses = Cache::tags($cacheArr['cacheTag'])->get($cacheArr['cacheKey']);
        } else {
            $stopwordses = $this->select('stopwords_id','words','replace')
                ->where('status', '=', '1')
                ->where('type', '=', '2')
                ->where('organization_id','=',$organization_id)
                ->get();
            Cache::tags($cacheArr['cacheTag'])->put($cacheArr['cacheKey'], $stopwordses, $this->CacheTime['Stopwords']);
        }
        foreach($stopwordses as $stopwords){
			foreach (explode(',', $stopwords->words) as $word){
                $replace = $stopwords->replace == '*' ? str_repeat('*', mb_strlen($word, 'utf-8')) : $stopwords->replace;
                $targetIndex = str_replace($word,$replace, $target);
                if($targetIndex != $target ){
                    return TRUE;
                }
			}
		}
        return FALSE;
    }
    
}